#include "bsp_I2C.h"

#include <stdio.h>

#include "lz_hardware.h"

int I2C_init(void)
{
    //1. e53用的I2C
    I2cBusIo m_ia_i2c0m2 = {
        .scl = {.gpio = GPIO0_PA1, .func = MUX_FUNC3, .type = PULL_NONE, .drv = DRIVE_KEEP, .dir = LZGPIO_DIR_KEEP, .val = LZGPIO_LEVEL_KEEP},
        .sda = {.gpio = GPIO0_PA0, .func = MUX_FUNC3, .type = PULL_NONE, .drv = DRIVE_KEEP, .dir = LZGPIO_DIR_KEEP, .val = LZGPIO_LEVEL_KEEP},
        .id = FUNC_ID_I2C0,
        .mode = FUNC_MODE_M2,
    };
    
    //初始化I2C
    if(I2cIoInit(m_ia_i2c0m2) != LZ_HARDWARE_SUCCESS)
    {
        printf("init I2C I2C0 io failed\n");
        return -1;
    }
    //设置I2C时钟频率为100K
    if(LzI2cInit(IA_I2C0, 100000) != LZ_HARDWARE_SUCCESS)
    {
        printf("init I2C I2C0 failed!\n");
        return -2;
    }

    //2. OLED用的I2C


    return 0;
}

int i2c_write_word(uint8_t SlaveAddr, uint8_t RegAddr, uint8_t data)
{
    uint8_t send_data[2] = {0};
    // uint32_t send_len = 2;
    send_data[0] = RegAddr;
    send_data[1] = data;

    if(LzI2cWrite(IA_I2C0, SlaveAddr, send_data, 2) != LZ_HARDWARE_SUCCESS)
    {
        printf("[i2c_write_word] LzI2cWrite error.\n");
        return -1;
    }
        
    
    return 0;
}

int i2c_read_word(uint8_t SlaveAddr, uint8_t RegAddr, uint8_t* data)
{
    if(LzI2cReadReg(IA_I2C0, SlaveAddr, &RegAddr, 1, data, 1) != LZ_HARDWARE_SUCCESS)
    {
        printf("[i2c_read_word] LzI2cReadReg error.\n");
        return -1;
    }
        

    return 0;
    // LzI2cRead(IA_I2C0, SlaveAddr, RegVal, 1);
}
